package com.jiyinit.web.core.mobile.util;

import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.common.util.GlobalsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * word2pdf
 * @author zhaolw
 * @version 1.0
 * @date 2018/10/9 10:28
 * @since 1.0
 */
public class Word2PdfUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(Word2PdfUtil.class);

    private static final String SOFFICE_FULL_PATH = GlobalsUtils.getValue("SOFFICE_FULL_PATH");

    public static void word2pdf(String inFullPath, String outPath) throws Exception {
        if (!new File(inFullPath).exists()) {
            throw new FileNotFoundException();
        }
        String command = String.format("%s/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", SOFFICE_FULL_PATH, inFullPath, outPath);
        String output = executeCommand(command);
        LogUtil.info(LOGGER, "exec command:[{}]\n" + "output: [{}]", command, output);

    }

    protected static String executeCommand(String command) throws IOException, InterruptedException {
        StringBuffer output = new StringBuffer();
        Process p;
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        try (
                InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader)
        ) {
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        }
        p.destroy();
        return output.toString();
    }
}
